package com.zhu.salesmanagement.network;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.SalesApplication;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CRCinfoItem;
import com.zhu.salesmanagement.models.CustomerItem;
import com.zhu.salesmanagement.models.CustomerShelfsItem;
import com.zhu.salesmanagement.models.IntegrationStandardItem;
import com.zhu.salesmanagement.models.PusherStoreItem;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.SyncView;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 获取附件门店
 */
public class SyncNearCustomerData {

    private static final int RAIDUS = 2000; //半径

    public static final int SYNC_FAILEDEND = 2;
    public static final int SYNC_SUCCESSEND = 3;
    public static final int SYNC_FAILEDEND_CUSTOMER = 5;
    public static final int SYNC_SUCCESSEND_CUSTOMER = 6;

    private static final int STTUP_GETNEARCUSOMERS = 0; //获取附件门店
    private static final int SETUP_GETCUSTOMER = 1; //获取对应门店的基础信息
    private static final int SETUP_GETCSHELF = 2; //获取对应门店的产品大类信息以及门店货架信息
    private static final int SETUP_GETISTANDARD = 3; //获取对应大区综合考评信息
    private static final int SETUP_GETCRC = 4; //获取对应门店最近一天的CRC资料
    private static final int SETUP_GETCRCOTHER = 5;  //获取对应门店最近一次的重要讯息
    private static final int SETUP_GETSCMSG = 6; //获取对应门店最近一次SC的重要讯息
    private static final int SETUP_GETPUSHERSTORE = 7; //获取对应门店的导购信息

    private static final int TYPE_NEAR = 0;
    private static final int TYPE_CUSTOMERS = 1;

    private Context mContext = null;
    private Handler mHandler = null;
    private int mConnectStep = -1;
    private int retryCount = 0;
    private ViewGroup mParent = null;
    private View mPopView = null;
    private LayoutInflater mLayoutInflater = null;
    private ImageView mImageView = null;
    private TextView mClewView = null;
    private AnimationDrawable mAnimation = null;
    private boolean isSyncing = false;
    private Location mCurLocation = null;
    private List<String> mNearCustomersList = null;
    private ArrayList<IntegrationStandardItem> mISlist = null;
    private ArrayList<CustomerItem> mCustomerList = null;
    private ArrayList<CRCinfoItem> mCRClist = null;
    private ArrayList<PusherStoreItem> mPusherList = null;
    private ArrayList<CustomerShelfsItem> mCSlist = null;
    private int mType = TYPE_NEAR;
    private VisitTaskInfo mVisitTaskInfo = null;

    /**
     * 构造函数
     * @param context 上线文
     * @param mLayoutInflater LayoutInflater
     * @param handler 结果
     * @param parent 父ViewGroup
     */
    public SyncNearCustomerData(Context context, LayoutInflater layoutInflater, Handler handler, ViewGroup parent){
        mContext = context;
        mHandler = handler;
        mParent = parent;
        mLayoutInflater = layoutInflater;
        mPopView = mLayoutInflater.inflate(R.layout.layout_popconnect, null);
        mPopView.setOnClickListener(null);

        setupView();
    }

    /**
     *设置界面 
     */
    private void setupView(){
        mImageView = (ImageView)(mPopView.findViewById(R.id.popconnect_animationImage));
        mClewView = (TextView)(mPopView.findViewById(R.id.popconnect_animationText));
    }

    /**
     * 显示联网界面
     */
    private void showView(){
        mAnimation = (AnimationDrawable) mImageView.getBackground();
        mAnimation.setLevel(0);
        mAnimation.start();
        mParent.addView(mPopView);
    }

    /**
     * 移除联网界面
     */
    public void remoView(){
        mAnimation.stop();
        mAnimation = null;
        mParent.removeView(mPopView);
    }

    /**
     * 开始获取
     * @param location 当前位置
     */
    public void statSync(Location location){
        mCurLocation = location;
        if(mCurLocation == null){
            return;
        }
        mVisitTaskInfo = null;
        mType = TYPE_NEAR;
        resetData();
        mConnectStep = -1;
        mClewView.setText(R.string.getneardata);
        showView();
        isSyncing = true;
        getNearCustomers();
    }

    /**
     * 开始获取客户数据
     * @param cid 客户id
     */
    public void statSync(VisitTaskInfo info){
    	 mType = TYPE_CUSTOMERS;
    	 resetData();
         mConnectStep = -1;
         mVisitTaskInfo = info;
         mClewView.setText(R.string.getcustomerdata);
         showView();
         isSyncing = true;
         mNearCustomersList = new ArrayList<String>();
         mNearCustomersList.add(info.id);
         getCustomer();
    }

    /**
     * 重置数据
     */
    private void resetData(){
        if(mNearCustomersList != null){
            mNearCustomersList.clear();
            mNearCustomersList = null;
        }
        if(mISlist != null){
            mISlist.clear();
            mISlist = null;
        }
        if(mCustomerList != null){
            mCustomerList.clear();
            mCustomerList = null;
        }
        if(mCSlist != null){
            mCSlist.clear();
            mCSlist = null;
        }
        if(mCRClist != null){
            mCRClist.clear();
            mCRClist = null;
        }
        if(mPusherList != null){
            mPusherList.clear();
            mPusherList = null;
        }
    }

    /**
     * 重新连接
     */
    private void retryConnect(){
        switch(mConnectStep){
            case STTUP_GETNEARCUSOMERS:
                getNearCustomers();
                break;
            case SETUP_GETCUSTOMER:
                getCustomer();
                break;
            case SETUP_GETCSHELF:
                getProductCategoryAndCustomerShelfOfCustomers();
                break;
            case SETUP_GETISTANDARD:
                getIntegrationStandard();
                break;
            case SETUP_GETCRC:
                getCRC();
                break;
            case SETUP_GETCRCOTHER:
                getCRCOther();
                break;
            case SETUP_GETSCMSG:
                getSCMsg();
                break;
            case SETUP_GETPUSHERSTORE:
                getPusherStore();
                break;
        }
    }

    /**
     * 获取附件门店
     */
    private void getNearCustomers(){
        mConnectStep = STTUP_GETNEARCUSOMERS;
        if(Actions.DEBUG){
            Log.e("zhu", "getNearCustomers");
        }
        PostMethod.requestNearCustomers(Util.mVerifyUserResult.id,
                Util.mVerifyUserResult.mUUID, mCurLocation.getLongitude(), mCurLocation.getLatitude(), RAIDUS, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        mCustomerList = ParseData.parseCustomer(result, mContext);
                        if(mCustomerList != null){
                            retryCount = 0;
                            syncSuccessEnd();//getCustomer();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 获取客户基础数据
     */
    private void getCustomer(){
        mConnectStep = SETUP_GETCUSTOMER;
        if(mNearCustomersList.size() == 0){
            getProductCategoryAndCustomerShelfOfCustomers();
            return;
        }
        PostMethod.requesCustomer(Util.mVerifyUserResult.id,
                Util.mVerifyUserResult.mUUID, mNearCustomersList, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        mCustomerList = ParseData.parseCustomer(result, mContext);
                        if(mCustomerList != null){
                            retryCount = 0;
                            getProductCategoryAndCustomerShelfOfCustomers();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getProductCategoryAndCustomerShelfOfCustomers
     */
    private void getProductCategoryAndCustomerShelfOfCustomers(){
        mConnectStep = SETUP_GETCSHELF;
        if(mNearCustomersList.size() == 0){
            getIntegrationStandard();
            return;
        }
        PostMethod.requesCustomerShelfs(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, mNearCustomersList,
                new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        mCSlist = ParseData.parseCustomerShelfs(result, mContext);
                        if (mCSlist != null) {
                            retryCount = 0;
                            getIntegrationStandard();
                        } else {
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getIntegrationStandard
     */
    private void getIntegrationStandard(){
        mConnectStep = SETUP_GETISTANDARD;
        if(mNearCustomersList.size() == 0){
            getCRC();
            return;
        }
        PostMethod.requestIntegrationStandard(Util.mVerifyUserResult.id,
                Util.mVerifyUserResult.mUUID, mNearCustomersList, new XMLRPCMethodCallback() {
                    public void callFinished(int status, Object result) {
                        mISlist = ParseData.parseStandards(result, mContext);
                        if(mISlist != null){
                            retryCount = 0;
                            getCRC();
                        }else{
                            syncFail();
                        }
                    }
                }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getCRC
     */
    private void getCRC(){
        mConnectStep = SETUP_GETCRC;
        if(mNearCustomersList.size() == 0){
            getCRCOther();
            return;
        }
        PostMethod.requesCRC(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, mNearCustomersList, new XMLRPCMethodCallback() {
                        public void callFinished(int status, Object result) {
                            mCRClist = ParseData.parseCRC(result, mContext);
                            if (mCRClist != null) {
                                retryCount = 0;
                                getCRCOther();
                            } else {
                                syncFail();
                            }
                        }
                    }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getCRCOther
     */
    private void getCRCOther(){
        mConnectStep = SETUP_GETCRCOTHER;
        if(mNearCustomersList.size() == 0){
            getSCMsg();
            return;
        }
        PostMethod.requesCRCOther(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, mNearCustomersList, new XMLRPCMethodCallback() {
                        public void callFinished(int status, Object result) {
                            boolean isSuccess = ParseData.parseCRCOther(result, mContext, mCRClist);
                            if (isSuccess) {
                                retryCount = 0;
                                getSCMsg();
                            } else {
                                syncFail();
                            }
                        }
                    }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getSCMsg
     */
    private void getSCMsg(){
        mConnectStep = SETUP_GETSCMSG;
        if(mNearCustomersList.size() == 0){
            getPusherStore();
            return;
        }
        PostMethod.requesSCMsg(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, mNearCustomersList, new XMLRPCMethodCallback() {
                        public void callFinished(int status, Object result) {
                        	 boolean success = ParseData.parseSCMsg(result, mContext, mCustomerList);
                             if (success) {
                                retryCount = 0;
                                getPusherStore();
                            } else {
                                syncFail();
                            }
                        }
                    }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * getPusherStore
     */
    private void getPusherStore(){
        mConnectStep = SETUP_GETPUSHERSTORE;
        if(mNearCustomersList.size() == 0){
            syncSuccessEnd();
            return;
        }
        PostMethod.requesPusherStore(Util.mVerifyUserResult.id,
                    Util.mVerifyUserResult.mUUID, mNearCustomersList, new XMLRPCMethodCallback() {
                        public void callFinished(int status, Object result) {
                        	mPusherList = ParseData.parsePusherStore(result, mContext);
                            if (mPusherList != null) {
                                retryCount = 0;
                                syncSuccessEnd();
                            } else {
                                syncFail();
                            }
                        }
                    }, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    /**
     * 成功获取
     */
    private void syncSuccessEnd(){
        if(Actions.DEBUG){
            Log.e("zhu","syncSuccessEnd");
        }
        saveSyncData();
        mConnectStep = -1;
        retryCount = 0;
        isSyncing = false;
        if(mType == TYPE_NEAR){
        	mHandler.sendEmptyMessage(SYNC_SUCCESSEND);
        }else{
        	mHandler.sendEmptyMessage(SYNC_SUCCESSEND_CUSTOMER);
        }
    }

    /**
     * 获取失败
     */
    private void syncFail(){
        if(Actions.DEBUG){
            Log.e("zhu","syncFail="+mConnectStep);
        }
        if(retryCount < 3){
            retryCount++;
            retryConnect();
        }else{
            retryCount = 0;
            mConnectStep = -1;
            isSyncing = false;
            if(mType == TYPE_NEAR){
            	mHandler.sendEmptyMessage(SYNC_FAILEDEND);
            }else{
            	mHandler.sendEmptyMessage(SYNC_FAILEDEND_CUSTOMER);
            }
        }
    }

    public boolean isSync(){
        return isSyncing;
    }

    /**
     * 销毁
     */
    public void destory(){
        resetData();
        mAnimation = null;
        mPopView = null;
        mImageView = null;
        if(mNearCustomersList != null){
            mNearCustomersList.clear();
            mNearCustomersList = null;
        }
    }

    private Map<String, Object> getMap(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("decLongitude", mCurLocation.getLongitude());
        map.put("decLatitude", mCurLocation.getLatitude());
        map.put("raidus", RAIDUS);
        return map;
    }

    /**
     * 保存同步数据
     */
    private void saveSyncData(){
    	SyncUtils.saveIntegrationStandardList(mContext, mISlist);
    	String deletecwhere = SyncUtils.saveCustomerList(mContext, mCustomerList);
    	SyncUtils.saveCustomerShelfsList(mContext, mCSlist);
        if(deletecwhere.length() > 1){
            mContext.getContentResolver().delete(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, deletecwhere, null);
        }
        SyncUtils.saveCRCinfoList(mContext, mCRClist);
        SyncUtils.savePusherStoreList(mContext, mPusherList);
        if(mVisitTaskInfo != null){
            CustomerItem item = getCustomerItem(mVisitTaskInfo.id);
            if(item != null){
                if(Actions.DEBUG){
                    Log.e("zhu",item.sCRCNearTime + "," +item.sSCNearTime);
                }
                mVisitTaskInfo.sCRCNearTime = item.sCRCNearTime;
                mVisitTaskInfo.sSCNearTime = item.sSCNearTime;
                mVisitTaskInfo.sMsg = item.sMsg;
            }
        }
    }

    private CustomerItem getCustomerItem(String cid){
        for(int i = 0; i < mCustomerList.size(); i++){
            CustomerItem item = mCustomerList.get(i);
            if(item.sCustomerID.equals(cid)){
                return item;
            }
        }
        return null;
    }
}
